import { parse } from 'querystring';
import moment from 'moment';
// @ts-ignore
// import { message } from 'antd';
import request from '@/utils/request';
import Cookies from 'js-cookie';
import currency from 'currency.js';
/* eslint no-useless-escape:0 import/prefer-default-export:0 */
const reg = /(((^https?:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+(?::\d+)?|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)$/;

const isUrl = (path: string): boolean => reg.test(path);

let UPDATA_TOKEN_TIME: any = null;
/**
 * 转大写中文
 */
const transferUppercase = (n: any): string => {
  /*  if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
       return "数据非法"; */
  if (!/^(0|\-*[1-9]\d*)(\.\d+)?$/.test(n)) return '数据非法';
  const fuhao = n.toString().indexOf('-') === 0 ? '负' : '';

  let unit = '千百拾亿千百拾万千百拾元角分';
  let str = '';
  n += '00';
  // 如果是负数就就截取
  if (fuhao === '负') {
    n = n.substring(1, n.length);
  }
  const p = n.indexOf('.');
  if (p >= 0) n = n.substring(0, p) + n.substr(p + 1, 2);
  unit = unit.substr(unit.length - n.length);
  for (let i = 0; i < n.length; i++)
    str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
  return (
    fuhao +
    str
      .replace(/零(千|百|拾|角)/g, '零')
      .replace(/(零)+/g, '零')
      .replace(/零(万|亿|元)/g, '$1')
      .replace(/(亿)万|壹(拾)/g, '$1$2')
      .replace(/^元零?|零分/g, '')
      .replace(/元$/g, '元整')
  );
};

const getPageQuery = () => parse(window.location.href.split('?')[1]);

const randomLenNum = (len: any, date?: any) => {
  let random = '';
  random = Math.ceil(Math.random() * 100000000000000)
    .toString()
    .substr(0, len || 4);
  if (date) random += Date.now();
  return random;
};

// 复制文本
const Copy = (id: any, callback: (res: any) => void, type?: any) => {
  // @ts-ignore
  var text = document.getElementById(id).innerText;
  if (type === "money") {
    text = text.replace(/,/g, '');
  }
  var input = document.createElement('input');
  input.setAttribute('id', 'copyInput');
  input.setAttribute('value', text);
  document.getElementsByTagName('body')[0].appendChild(input);
  // @ts-ignore
  document.getElementById('copyInput').select();
  const tag = document.execCommand('Copy');
  callback(tag);
  // @ts-ignore
  document.getElementById('copyInput').remove();
};


// 在活动状态时，更新token
const continueUpdateToken = () => {
  if (UPDATA_TOKEN_TIME) clearTimeout(UPDATA_TOKEN_TIME);
  UPDATA_TOKEN_TIME = setTimeout(() => {
    request('/sys/refreshSession', {
      method: 'get',
    });
    continueUpdateToken();
  }, 20 * 60 * 1000);
};

// 将图片转换为Base64
function getImgToBase64(url: string, callback?: (res: any) => void) {
  let canvas = document.createElement('canvas');
  const ctx = canvas.getContext('2d');
  const img = new Image();
  img.crossOrigin = 'Anonymous';
  img.onload = function() {
    canvas.height = img.height;
    canvas.width = img.width;
    // @ts-ignore
    ctx.drawImage(img, 0, 0);
    const dataURL = canvas.toDataURL('image/png');
    callback && callback(dataURL);
    // @ts-ignore
    canvas = null;
  };
  img.src = url;
}

// 将base64转换为文件
function Base64toFile(dataurl: any, filename: string) {
  const arr = dataurl.split(',');
  const mime = arr[0].match(/:(.*?);/)[1];
  const bstr = window.atob(arr[1]);
  let n = bstr.length;
  const u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new File([u8arr], filename, { type: mime });
}

function deepClone(obj: any): any {
  var _obj = JSON.stringify(obj),
    objClone = JSON.parse(_obj);
  return objClone;
}

function treeToArray(data: any) {
  function jsonToArray(nodes: any): any {
    var r = [];
    if (Array.isArray(nodes)) {
      for (var i = 0, l = nodes.length; i < l; i++) {
        r.push(nodes[i]); // 取每项数据放入一个新数组
        if (Array.isArray(nodes[i]['children']) && nodes[i]['children'].length > 0)
          // 若存在children则递归调用，把数据拼接到新数组中，并且删除该children
          r = r.concat(jsonToArray(nodes[i]['children']));
        delete nodes[i]['children'];
      }
    }
    return r;
  }
  return jsonToArray(data);
}
function arrayToTree(treeArray: any): any {
  var r = [];
  var tmpMap = {};
  for (var i = 0, l = treeArray.length; i < l; i++) {
    // 以每条数据的id作为obj的key值，数据作为value值存入到一个临时对象里面
    tmpMap[treeArray[i]['id']] = treeArray[i];
  }
  for (i = 0, l = treeArray.length; i < l; i++) {
    var key = tmpMap[treeArray[i]['parentId']];
    if (key) {
      // 如果这个数据没有children
      if (!key['children']) {
        key['children'] = [];
        key['children'].push(treeArray[i]);
      } else {
        key['children'].push(treeArray[i]);
      }
    } else {
      //如果没有这个Key值，就代表找不到属于哪个数据，那就代表没有父级,直接放在最外层
      r.push(treeArray[i]);
    }
  }
  return r;
}
function menuToTree(treeArray: any): any {
  var r = [];
  var tmpMap = {};
  for (var i = 0, l = treeArray.length; i < l; i++) {
    // 以每条数据的id作为obj的key值，数据作为value值存入到一个临时对象里面
    tmpMap[treeArray[i]['rid']] = treeArray[i];
  }
  for (i = 0, l = treeArray.length; i < l; i++) {
    var key = tmpMap[treeArray[i]['pid']];
    if (key) {
      // 如果这个数据没有children
      if (!key['children']) {
        key['children'] = [];
        key['children'].push(treeArray[i]);
      } else {
        key['children'].push(treeArray[i]);
      }
    } else {
      //如果没有这个Key值，就代表找不到属于哪个数据，那就代表没有父级,直接放在最外层
      r.push(treeArray[i]);
    }
  }
  return r;
}

function updateXToken() {
  if(!Cookies.get('Authorization')) return;
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
      let res = JSON.parse(xhr.responseText);
      if (res.code === 1) {
        Cookies.set('X_token', res.data);
      }
    }
  };
  xhr.open('GET', 'admin/admin/t', true);
  xhr.setRequestHeader('Authorization', `Bearer ${Cookies.get('Authorization')}`);
  xhr.setRequestHeader('Content-Type', 'application/json');
  xhr.setRequestHeader('Accept', 'application/json');
  // xhr.onload = function () {
  //     if (this.status === 200) {
  //         var res = this.response;
  //         console.log(res)
  //     }
  // };
  xhr.send();
}

function authPermissions(id: any) {
  // @ts-ignore
  let permissions = JSON.parse(localStorage.getItem('Permissions'));
  let newPermissions = deepClone(permissions);
  let permissionsArr = treeToArray(newPermissions).map((item: any) => {
    return item.id;
  });

  permissionsArr.push(0);
  if (permissionsArr.indexOf(id) !== -1) {
    return true;
  } else {
    return false;
  }
}
function debounce(func: any, wait: any, immediate?: any) {
  //@ts-ignore
  let timeout, args, context, timestamp, result;

  const later = function() {
    // 据上一次触发时间间隔
    // @ts-ignore
    const last = +new Date() - timestamp;

    // 上次被包装函数被调用时间间隔 last 小于设定时间间隔 wait
    if (last < wait && last > 0) {
      timeout = setTimeout(later, wait - last);
    } else {
      timeout = null;
      // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
      if (!immediate) {
        // @ts-ignore
        result = func.apply(context, args);
        if (!timeout) context = args = null;
      }
    }
  };
  // @ts-ignore
  return function(...args) {
    // @ts-ignore
    context = this;
    timestamp = +new Date();
    // @ts-ignore
    const callNow = immediate && !timeout;
    // 如果延时不存在，重新设定延时
    // @ts-ignore
    if (!timeout) timeout = setTimeout(later, wait);
    if (callNow) {
      // @ts-ignore
      result = func.apply(context, args);
      // @ts-ignore
      context = args = null;
    }
    // @ts-ignore
    return result;
  };
}
function platFormTitle() {
  switch (process.env.PLATFORM) {
    case 'trial':
      return '试玩平台'
    default:
      return '阳光考勤系统'
  }
}

const formatColor = (text: any) => {
  let num = parseFloat(text);
  if (num < 10000) {
    return '#666555';
  } else if (num >= 10000 && num < 100000) {
    return '#3e34fc';
  } else if (num >= 100000) {
    return 'red';
  } else {
    return '#666555';
  }
};
const cutZero = (old: any) => {
  //拷贝一份 返回去掉零的新串
  let newstr = old;
  //循环变量 小数部分长度
  var leng = old.length - old.indexOf(".") - 1
  //判断是否有效数
  if (old.indexOf(".") > -1) {
    //循环小数部分
    for (let i = leng; i > 0; i--) {
      //如果newstr末尾有0
      if (newstr.lastIndexOf("0") > -1 && newstr.substr(newstr.length - 1, 1) === 0) {
        var k = newstr.lastIndexOf("0");
        //如果小数点后只有一个0 去掉小数点
        if (newstr.charAt(k - 1) === ".") {
          return newstr.substring(0, k - 1);
        } else {
          //否则 去掉一个0
          newstr = newstr.substring(0, k);
        }
      } else {
        //如果末尾没有0
        return newstr;
      }
    }
  }
  return old;
}
const formatBalance = (balance: any = 0, bit: any = process.env.PRECISION) => {
  let newbalance = cutZero(currency(balance, { separator: ',', precision: bit }).format())
  return newbalance
} 
const formatCurrentDay = () => {
  let prevDay = moment().add(-1, "days").format("YYYY-MM-DD");
  let currentDay = moment().format("YYYY-MM-DD");
  let currentDate = new Date().getTime();
  let toDateM = moment(`${currentDay} 07:00:00`).format();
  let toDate = new Date(toDateM).getTime();
  if (currentDate < toDate) {
    return prevDay
  } else {
    return currentDay
  }
}

const getFormatDay = (date?: any) => {
  const day1 = isRangeDate(moment().format("YYYY/MM/DD 07:00:00"),moment().format("YYYY/MM/DD 23:59:59"));
  // const day2 = isRangeDate(moment().format("YYYY-MM-DD 00:00:00").toString(),moment().format("YYYY-MM-DD 07:00:00").toString())
  if(day1) {
    const start = moment(date? date : new Date()).format("YYYY-MM-DD 07:00:00")
    const end = moment(date? date : new Date()).add(1,'days').format("YYYY-MM-DD 07:00:00")
    return {
      start,
      end
    }
  } else {
    const start = moment(date? date : new Date()).subtract(1,'day').format("YYYY-MM-DD 07:00:00");
    const end = moment(date? date : new Date()).format("YYYY-MM-DD 07:00:00");
    return {
      start: start,
      end
    }
  }
}
const isRangeDate = (beginDateStr: string, endDateStr:string) => {
    var curDate = new Date().getTime(),
        beginDate = new Date(beginDateStr).getTime(),
        endDate = new Date(endDateStr).getTime();
    if (curDate >= beginDate && curDate <= endDate) {
        return true;
    }
    return false;
}
export {
  isUrl,
  transferUppercase,
  getPageQuery,
  randomLenNum,
  Copy,
  continueUpdateToken,
  getImgToBase64,
  Base64toFile,
  deepClone,
  treeToArray,
  arrayToTree,
  menuToTree,
  updateXToken,
  authPermissions,
  debounce,
  platFormTitle,
  formatColor,
  cutZero,
  formatBalance,
  formatCurrentDay,
  getFormatDay
};
